<?php

namespace common\services\WXLogin;

use Yii;
use common\services\WXpay\WechatPay;
use common\models\kaoguobao\WechatUser;
use common\models\kaoguobao\PublicParams;

class WeiXinLoginService{

    public $appId;
    public $appSecret;

    function __construct()
    {
        $this->config       = Yii::$app->params['wx'];      // 获取微信相关配置
        $this->appId        = $this->config['appId'];       // 公众号ID
        $this->appSecret    = $this->config['appSecret'];   // 公众号key
        $this->redirectUri  = $this->config['redirectUri']; // 首页授权地址
//        $this->grantType    = $this->config['grantType'];   // 获取token参数
//        $this->mchId        = $this->config['mchId'];       // 商户id
//        $this->payKey       = $this->config['payKey'];      // 支付key
    }

    public function get_authorize_url($redirect_uri = '',$state = 'funfind')
    {
        $redirect_uri = urlencode($redirect_uri);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appId}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
    }

    //用户授权接口：获取access_token、openId等；获取并保存用户资料到数据库
    public function getAccesstoken()
    {
        $code   = $_GET["code"];
        $requestUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appId.'&secret='.$this->appSecret.'&code='.$code.'&grant_type=authorization_code';
        $result = $this->handleReturnResult($requestUrl);
        $result = $this->response($result);
        //获取token和openid成功，数据解析
        $access_token   = $result['access_token'];
        $refresh_token  = $result['refresh_token'];
        $openid         = $result['openid'];

        //请求微信接口，获取用户信息
        $userInfo = $this->getUnionID($access_token,$openid);
        $userInfo = $this->response($userInfo);

        $userCheck = WechatUser::find()->where(['openid'=>$openid])->limit(1)->one();

        if(empty($userCheck)){
            $userCheck = new WechatUser();
            $userCheck->openid = $openid;
        }
        $userCheck->nickname        = $userInfo['nickname'];
        $userCheck->sex             = $userInfo['sex'];
        $userCheck->headimgurl      = $userInfo['headimgurl'];
        $userCheck->country         = $userInfo['country'];
        $userCheck->province        = $userInfo['province'];
        $userCheck->city            = $userInfo['city'];
        $userCheck->access_token    = $access_token;
        $userCheck->refresh_token   = $refresh_token;
        if($userCheck->save()){
            return $openid;
        }
    }

    /**
     * 解析json
     * @param $text
     * @return mixed
     */
    private function response($text)
    {
        return json_decode($text, true);
    }

    /**
     * 返回微信code地址的请求
     * @param string $redirect_uri
     * @param string $response_type
     * @param string $scope
     * @return string
     */
    public function getWeiXinCode($response_type = 'code', $scope = 'snsapi_userinfo')
    {
        $wxUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appId}&redirect_uri={$this->redirectUri}&response_type={$response_type}&scope={$scope}&state=1#wechat_redirect";
        header("Location:".$wxUrl);
    }

    /**
     * 获取用户微信用户open_id，access_token等
     * @param string $code
     * @return mixed
     */
    public function getWeiXinUserOpenId($code = '')
    {
        // 请求微信获取AccessToken的地址 参数已经默认获取了，所以不需要传参数
        $redis = Yii::$app->redis;
        $redisToken = $redis->get('wechat:accessToken');
        if(!empty($redisToken)){
            $redisToken = json_decode($redisToken);
        }else{
            $getToken = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appId}&secret={$this->appSecret}&code={$code}&grant_type=authorization_code";
            $result = $this->handleReturnResult($getToken);
            $redisToken = json_decode($result);
            if(!empty($redisToken->access_token)){
                $redis->set('wechat:accessToken', $result);
                $redis->expire('wechat:accessToken', 7000);
            }
        }
        return $redisToken;
    }

    /**
     * 刷新当前用户登录态问题
     * @param string $refreshToken
     * @return mixed
     */
    public function getRefreshToken($refreshToken = '')
    {
        $getToken = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->appId}&grant_type=refresh_token&refresh_token={$refreshToken}";
        return $this->handleReturnResult($getToken);
    }

    /**
     * 获取用户微信相关个人信息
     * @param string $accessToken
     * @param string $openId
     * @return mixed
     */
    public function getUnionID($accessToken = '', $openId = '', $refresh_token = '')
    {
        $getToken = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openId}";
        $result = $this->handleReturnResult($getToken);
        $result = json_decode($result);
        if(!empty($result->openid)){
            $wechat = WechatUser::find()->where(['openid' => $result->openid])->limit(1)->one();
            if(empty($wechat)){
                $wechat = new WechatUser();
                $wechat->openid     = $result->openid;
                $wechat->sex        = $result->sex;
                $wechat->province    = $result->province;
                $wechat->city       = $result->city;
            }
            $wechat->nickname       = $result->nickname;
            $wechat->headimgurl     = $result->headimgurl;
            $wechat->access_token   = $accessToken;
            $wechat->refresh_token  = $refresh_token;
            if($wechat->save()){
                $identity = WechatUser::findOne($wechat->attributes['id']);
                Yii::$app->user->login($identity);
                return $wechat;
            }
        }
    }

    /**
     * 打开一个接口 返回对应的参数
     * @param string $url
     * @return mixed
     */
    public function handleReturnResult($url = '')
    {
        $weather = curl_init();
        curl_setopt($weather,CURLOPT_URL,$url);
        curl_setopt($weather, CURLOPT_SSL_VERIFYPEER, false); //如果接口URL是https的,我们将其设为不验证,如果不是https的接口,这句可以不用加
        curl_setopt($weather,CURLOPT_RETURNTRANSFER,true);
        $data    = curl_exec($weather);
        curl_close($weather);
        return $data;
    }

    //微信支付接口：打包支付数据
    public function wechatPayService($openId = '', $amount = 0, $orderId, $orderBody = '', $notifyUrl){
        $timestamp = strval(time());
        //支付打包
        $wx_pay = new WechatPay($this->mchId, $this->appId, $this->payKey);
        $package = $wx_pay->createJsBizPackage($openId, $amount, $orderId, $orderBody, $notifyUrl, $timestamp);
        return $package;
    }

    public function wechatPayConfig($url = ''){
        $wx_pay = new WechatPay($this->mchId, $this->appId, $this->payKey);
        $package = $wx_pay->getSignPackage($url);
        return $package;
    }



}